package com.joney.backstage.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.gson.Gson;
import com.joney.common.annotation.Auth;
import com.joney.backstage.constant.Constants;
import com.joney.backstage.constant.Permissions;
import com.joney.backstage.constant.ReqURLs;
import com.joney.backstage.dto.Login4InnerFrameReq;
import com.joney.backstage.dto.LoginReq;
import com.joney.backstage.dto.UserAddReq;
import com.joney.backstage.dto.UserEditReq;
import com.joney.backstage.dto.UserRoleRsp;
import com.joney.backstage.service.UserService;
import com.joney.common.exception.DefaultException;
import com.joney.common.pojo.Datagrid;
import com.joney.common.pojo.Result;
import com.joney.common.utils.CookieUtil;
import com.joney.common.utils.EncryptUtil;
import com.joney.common.utils.JwtToken;
import com.joney.common.utils.MD5Util;
import com.joney.common.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.plugins.Page;
import com.joney.backstage.entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器，参考源码测试用例：
 * <p>
 * /mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java
 */
@Controller
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @PostMapping(ReqURLs.USER_LOGIN)
    @ResponseBody
    public Result login(@RequestParam String param, HttpServletRequest request, HttpServletResponse response) {
        Result rt = new Result();
        String json = null;
        try {
            json = EncryptUtil.aesDecrypt(param);
        } catch (Exception e) {
            LOGGER.error("登录信息解析异常");
            throw new DefaultException("登录信息解析异常");
        }
        LoginReq req = new Gson().fromJson(json,LoginReq.class);
        String token = userService.login(req, WebUtil.getIp(request));
        response.setHeader(Constants.HEADER_KEY_TOKEN,token);
        rt.setData(token);
        return rt;
    }

    @PostMapping(ReqURLs.USER_INNER_PAGE_FRAME_LOGIN)
    @ResponseBody
    public Result innerFrameLogin(@RequestParam String param, HttpServletRequest request, HttpServletResponse response) {
        Result rt = new Result();
        String json = null;
        try {
            json = EncryptUtil.aesDecrypt(param);
        } catch (Exception e) {
            LOGGER.error("登录信息解析异常");
            throw new DefaultException("登录信息解析异常");
        }
        Login4InnerFrameReq req = new Gson().fromJson(json,Login4InnerFrameReq.class);
        String token = userService.innerFrameLogin(req, WebUtil.getIp(request));
        response.setHeader(Constants.HEADER_KEY_TOKEN,token);
        rt.setData(token);
        return rt;
    }

    @GetMapping(ReqURLs.USER_LOGOUT)
    @ResponseBody
    public Result logout(HttpServletRequest request) {
        String token = CookieUtil.getTokenByCookie(request);
        userService.logout(token);
        return new Result();
    }

    @GetMapping(ReqURLs.USER_MGR)
    @Auth(Permissions.SYS_USER_VIEW)
    public String index(ModelMap model,
                        @RequestParam(required = false) Integer userId,
                        @RequestParam(required = false) String kind) {
        String url = "sys_base/user_mgr";
        if(kind != null && kind.equals("role")){
            model.put("userId",userId);
            url = "sys_base/user_bind_role";
        }
        model.put("authMap",userService.getMgrPermission(JwtToken.getLoginUserId().intValue()));
        return url;
    }

    @GetMapping(ReqURLs.USER_LIST)
    @ResponseBody
    @Auth(Permissions.SYS_USER_VIEW)
    public Datagrid list(Page page,
                         @RequestParam(required = false) String loginName,
                         @RequestParam(required = false) String phone,
                         @RequestParam(required = false) String email,
                         @RequestParam(required = false) Integer state) {
        EntityWrapper wrapper = new EntityWrapper<User>();
        if(loginName != null){
            wrapper.like("login_name",loginName);
        }
        if(phone != null){
            wrapper.like("phone",phone);
        }
        if(email != null){
            wrapper.like("email",email);
        }
        if(state != null){
            wrapper.eq("state",state);
        }
        Page<User> pageInfo = userService.selectPage(page,wrapper);
        return new Datagrid(pageInfo.getTotal(),pageInfo.getRecords());
    }


    @PostMapping(ReqURLs.USER_INSERT)
    @ResponseBody
    @Auth(Permissions.SYS_USER_ADD)
    public Result insert(@RequestBody @Validated UserAddReq params) {
        User temp = new User();
        BeanUtils.copyProperties(params,temp);
        temp.setCreateUser(JwtToken.getLoginUserId().intValue());
        temp.setPassword(MD5Util.encode(Constants.DEFAULT_INIT_CIPHER));
        if(!userService.insert(temp)){
            return Result.fail();
        }
        return Result.success();
    }

    @PostMapping(ReqURLs.USER_UPDATE)
    @ResponseBody
    @Auth(Permissions.SYS_USER_EDIT)
    public Result update(@RequestBody @Validated UserEditReq params) {
        return userService.updateUser(params,JwtToken.getLoginUserId().intValue());
    }

    @GetMapping(ReqURLs.USER_REMOVE)
    @ResponseBody
    @Auth(Permissions.SYS_USER_DEL)
    public Result remove(@RequestParam int id) {
        if(!userService.deleteById(id)){
            return Result.fail("删除失败，请刷新重试！");
        }
        return Result.success();
    }

    @GetMapping(ReqURLs.USER_EDIT)
    @Auth(Permissions.SYS_USER_VIEW)
    public String detail(@RequestParam int id,ModelMap model) {
        model.put("data",userService.selectById(id));
        return "sys_base/user_edit";
    }

    @GetMapping(ReqURLs.USER_QUERY_BIND_ROLE)
    @ResponseBody
    @Auth(Permissions.SYS_USER_ROLE_VIEW)
    public Datagrid queryBindRole(Page page,
                                  @RequestParam int userId,
                                  @RequestParam int bindState,
                                  @RequestParam(required = false) String roleName) {
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("roleName",roleName);
        List<UserRoleRsp> list = null;
        if(bindState ==1){ //已绑定的
            list = userService.queryBind(page,params);
        }else{
            list = userService.queryNotBindRole(page,params);
        }
        return new Datagrid(page.getTotal(),list);
    }
    @GetMapping(ReqURLs.USER_BIND_ROLE)
    @ResponseBody
    @Auth(Permissions.SYS_USER_ROLE_BIND)
    public Result bindRole(@RequestParam int userId,
                           @RequestParam int bindState,
                           @RequestParam String roleIds) {
        return userService.bindRole(userId,bindState,roleIds,JwtToken.getLoginUserId().intValue());
    }

    @PostMapping(ReqURLs.USER_CHANGE_PWD)
    @ResponseBody
    public Result changePwd(@RequestParam String param, HttpServletRequest request) {   //也可以使用@RequestParam(value="username",required=true)，如果上传的是json对象的话
        String token = CookieUtil.getTokenByCookie(request);
       return userService.changePwd(param,token);
    }
}
